#include <stdio.h>
#include <stdlib.h>
#include "tailq.h"
#include <time.h>

#include "num.h"
#include "time_count.h"

//队列中的元素结构体。它有一个值，并且有前向指针和后向指针
//通过前后像指针，把队列中的节点(元素)连接起来

struct student_t
{
	int id;
	int age;
	TAILQ_ENTRY(student_t) entry;
    // struct {								\
    //     struct student_t *tqe_next;	/* next element */			\
    //     struct student_t **tqe_prev;	/* address of previous next element */	\
    // } entry;
};

struct school_t
{
    // 队列头，它有两个指针，分别指向队列的头和尾
	TAILQ_HEAD(student_head_t, student_t) student_qh;
    // struct student_head_t {								\
    // 	struct student_t *tqh_first;	/* first element */			\
    // 	struct student_t **tqh_last;	/* addr of last next element */		\
    // };
	char name[20];
	char location[20];
};

struct student_t *st[STUDENT_NUM] = {NULL};

int main(int argc, char **argv)
{

// ========================= 尾插 ================================
	printf("======= tailq 尾插 ===========: ");
	struct school_t sc = {
		.name = "Peking",
		.location = "China"
	};
    int i;

    TAILQ_INIT(&sc.student_qh);
    // do {
    //     (&sc.student_qh)->tqh_first = NULL;
    //     (&sc.student_qh)->tqh_last = &(&sc.student_qh)->tqh_first;
    // } while (0);

	for (i = 0; i < STUDENT_NUM; i++) {
		st[i] = (struct student_t *)malloc(sizeof(struct student_t));
		if (st[i] == NULL)
		{
			perror("malloc failed");
			return -1;
		}
		st[i]->id = i;
		st[i]->age = i + STUDENT_NUM;
	}

	struct timespec tp_s = {0};
	tm_start(&tp_s);

    for (i = 0; i < STUDENT_NUM; i++)
    {
        TAILQ_INSERT_TAIL(&sc.student_qh, st[i], entry); //在队尾插入数据
    }

    struct student_t *p = NULL;
    TAILQ_FOREACH(p, &sc.student_qh, entry) //用foreach遍历所有元素
    {
        // printf("id:[%d]  age[%d]\n", p->id, p->age);
    }
	tm_sub(&tp_s);

	for (i = 0; i < STUDENT_NUM; i++)
    {
        free(st[i]);
    }
// ========================= 头插 ================================
	printf("======= tailq 头插 ===========: ");
	struct school_t sc2 = {
		.name = "Peking",
		.location = "China"
	};

    TAILQ_INIT(&sc2.student_qh);
    // do {
    //     (&sc.student_qh)->tqh_first = NULL;
    //     (&sc.student_qh)->tqh_last = &(&sc.student_qh)->tqh_first;
    // } while (0);

	for (i = 0; i < STUDENT_NUM; i++) {
		st[i] = (struct student_t *)malloc(sizeof(struct student_t));
		if (st[i] == NULL)
		{
			perror("malloc failed");
			return -1;
		}
		st[i]->id = i;
		st[i]->age = i + STUDENT_NUM;
	}

	tm_start(&tp_s);

    for (i = 0; i < STUDENT_NUM; i++)
    {
        TAILQ_INSERT_HEAD(&sc2.student_qh, st[i], entry); //在队尾插入数据
    }

    TAILQ_FOREACH(p, &sc2.student_qh, entry) //用foreach遍历所有元素
    {
        // printf("id:[%d]  age[%d]\n", p->id, p->age);
    }
	tm_sub(&tp_s);

	for (i = 0; i < STUDENT_NUM; i++)
    {
        free(st[i]);
    }
}

